package com.huawei.zyb.taskManager.interfaces.rest;

import com.huawei.zyb.taskManager.application.requirement.RequirementApplicationService;
import com.huawei.zyb.taskManager.application.requirement.dto.RequirementDTO;
import com.huawei.zyb.taskManager.application.service.ReferenceDocumentApplicationService;
import com.huawei.zyb.taskManager.application.service.dto.ReferenceDocumentDTO;
import com.huawei.zyb.taskManager.domain.requirement.valueobject.RequirementPriority;
import com.huawei.zyb.taskManager.domain.requirement.valueobject.RequirementStatus;
import com.huawei.zyb.taskManager.domain.shared.BusinessException;
import com.huawei.zyb.taskManager.interfaces.rest.request.AddDocumentRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;
import java.util.List;

/**
 * 需求控制器
 */
@RestController
@RequestMapping("/api/requirements")
public class RequirementController {
    
    private final RequirementApplicationService requirementApplicationService;
    private final ReferenceDocumentApplicationService referenceDocumentApplicationService;
    
    @Autowired
    public RequirementController(RequirementApplicationService requirementApplicationService,
                               ReferenceDocumentApplicationService referenceDocumentApplicationService) {
        this.requirementApplicationService = requirementApplicationService;
        this.referenceDocumentApplicationService = referenceDocumentApplicationService;
    }
    
    /**
     * 创建需求请求对象
     */
    public static class CreateRequirementRequest {
        @NotBlank(message = "需求标题不能为空")
        @Size(max = 200, message = "需求标题长度不能超过200个字符")
        private String title;
        
        @Size(max = 2000, message = "需求描述长度不能超过2000个字符")
        private String description;
        
        @NotNull(message = "需求优先级不能为空")
        private RequirementPriority priority;
        
        @NotNull(message = "项目ID不能为空")
        @Positive(message = "项目ID必须为正数")
        private Long projectId;
        
        private String ownerId;
        
        private String expectedCompletionDate;
        
        private List<ReferenceDocumentRequest> referenceDocuments;
        
        // Getters and Setters
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public RequirementPriority getPriority() { return priority; }
        public void setPriority(RequirementPriority priority) { this.priority = priority; }
        public Long getProjectId() { return projectId; }
        public void setProjectId(Long projectId) { this.projectId = projectId; }
        public String getOwnerId() { return ownerId; }
        public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
        public String getExpectedCompletionDate() { return expectedCompletionDate; }
        public void setExpectedCompletionDate(String expectedCompletionDate) { this.expectedCompletionDate = expectedCompletionDate; }
        public List<ReferenceDocumentRequest> getReferenceDocuments() { return referenceDocuments; }
        public void setReferenceDocuments(List<ReferenceDocumentRequest> referenceDocuments) { this.referenceDocuments = referenceDocuments; }

        @Override
        public String toString() {
            return "CreateRequirementRequest{" +
                    "title='" + title + '\'' +
                    ", description='" + description + '\'' +
                    ", priority=" + priority +
                    ", projectId=" + projectId +
                    ", ownerId=" + ownerId +
                    ", expectedCompletionDate=" + expectedCompletionDate +
                    ", referenceDocuments=" + referenceDocuments +
                    '}';
        }
    }
    
    /**
     * 参考文档请求对象
     */
    public static class ReferenceDocumentRequest {
        private String title;
        private String url;
        
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public String getUrl() { return url; }
        public void setUrl(String url) { this.url = url; }
        
        @Override
        public String toString() {
            return "ReferenceDocumentRequest{" +
                    "title='" + title + '\'' +
                    ", url='" + url + '\'' +
                    '}';
        }
    }
    
    /**
     * 更新需求请求对象
     */
    public static class UpdateRequirementRequest {
        @NotBlank(message = "需求标题不能为空")
        @Size(max = 200, message = "需求标题长度不能超过200个字符")
        private String title;
        
        @Size(max = 2000, message = "需求描述长度不能超过2000个字符")
        private String description;
        
        @NotNull(message = "需求优先级不能为空")
        private RequirementPriority priority;
        
        // Getters and Setters
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public RequirementPriority getPriority() { return priority; }
        public void setPriority(RequirementPriority priority) { this.priority = priority; }
    }
    
    /**
     * 创建需求
     */
    @PostMapping
    public ResponseEntity<?> createRequirement(@Valid @RequestBody CreateRequirementRequest request) {
        System.out.println("接收到的请求数据: " + request);
        System.out.println("ownerId: " + request.getOwnerId());
        try {
            RequirementDTO requirement = requirementApplicationService.createRequirement(
                request.getTitle(),
                request.getDescription(),
                request.getPriority() != null ? request.getPriority().name() : null,
                request.getProjectId(),
                request.getOwnerId(),
                request.getExpectedCompletionDate()
            );
            
            // 处理参考文档
            if (request.getReferenceDocuments() != null && !request.getReferenceDocuments().isEmpty()) {
                String uploader = "system"; // 临时使用系统默认值
                String documentType = "general"; // 默认文档类型
                
                for (ReferenceDocumentRequest docRequest : request.getReferenceDocuments()) {
                    if (docRequest.getTitle() != null && !docRequest.getTitle().trim().isEmpty() &&
                        docRequest.getUrl() != null && !docRequest.getUrl().trim().isEmpty()) {
                        try {
                            referenceDocumentApplicationService.createReferenceDocument(
                                requirement.getId().toString(),
                                docRequest.getTitle(),
                                docRequest.getUrl(),
                                null, // description
                                documentType,
                                uploader
                            );
                        } catch (Exception e) {
                            System.err.println("创建参考文档失败: " + e.getMessage());
                            // 继续处理其他文档，不中断需求创建
                        }
                    }
                }
            }
            
            return ResponseEntity.status(HttpStatus.CREATED).body(requirement);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 根据ID查找需求
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> findRequirementById(@PathVariable Long id) {
        try {
            RequirementDTO requirement = requirementApplicationService.findById(id);
            return ResponseEntity.ok(requirement);
        } catch (BusinessException e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 更新需求信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateRequirement(@PathVariable Long id, @Valid @RequestBody UpdateRequirementRequest request) {
        try {
            requirementApplicationService.updateRequirement(
                id,
                request.getTitle(),
                request.getDescription(),
                request.getPriority()
            );
            // 返回更新后的需求数据
            RequirementDTO updatedRequirement = requirementApplicationService.findById(id);
            return ResponseEntity.ok(updatedRequirement);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 删除需求
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteRequirement(@PathVariable Long id) {
        try {
            requirementApplicationService.deleteRequirement(id);
            return ResponseEntity.noContent().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 分配负责人
     */
    @PostMapping("/{id}/assign")
    public ResponseEntity<?> assignOwner(@PathVariable Long id, @RequestParam String ownerId) {
        try {
            requirementApplicationService.assignOwner(id, ownerId);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 审批需求
     */
    @PostMapping("/{id}/approve")
    public ResponseEntity<?> approveRequirement(@PathVariable Long id) {
        try {
            requirementApplicationService.approveRequirement(id);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 拒绝需求
     */
    @PostMapping("/{id}/reject")
    public ResponseEntity<?> rejectRequirement(@PathVariable Long id) {
        try {
            requirementApplicationService.rejectRequirement(id);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 开始需求
     */
    @PostMapping("/{id}/start")
    public ResponseEntity<?> startRequirement(@PathVariable Long id) {
        try {
            requirementApplicationService.startRequirement(id);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 暂停需求
     */
    @PostMapping("/{id}/pause")
    public ResponseEntity<?> pauseRequirement(@PathVariable Long id) {
        try {
            requirementApplicationService.pauseRequirement(id);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 恢复需求
     */
    @PostMapping("/{id}/resume")
    public ResponseEntity<?> resumeRequirement(@PathVariable Long id) {
        try {
            requirementApplicationService.resumeRequirement(id);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 完成需求
     */
    @PostMapping("/{id}/complete")
    public ResponseEntity<?> completeRequirement(@PathVariable Long id) {
        try {
            requirementApplicationService.completeRequirement(id);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 取消需求
     */
    @PostMapping("/{id}/cancel")
    public ResponseEntity<?> cancelRequirement(@PathVariable Long id) {
        try {
            requirementApplicationService.cancelRequirement(id);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 激活需求
     */
    @PostMapping("/{id}/activate")
    public ResponseEntity<?> activateRequirement(@PathVariable Long id) {
        try {
            requirementApplicationService.activateRequirement(id);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 根据项目ID查找需求列表
     */
    @GetMapping("/project/{projectId}")
    public ResponseEntity<List<RequirementDTO>> findRequirementsByProjectId(@PathVariable Long projectId) {
        List<RequirementDTO> requirements = requirementApplicationService.findByProjectId(projectId);
        return ResponseEntity.ok(requirements);
    }
    
    /**
     * 根据负责人ID查找需求列表
     */
    @GetMapping("/owner/{ownerId}")
    public ResponseEntity<List<RequirementDTO>> findRequirementsByOwnerId(@PathVariable String ownerId) {
        List<RequirementDTO> requirements = requirementApplicationService.findByOwnerId(ownerId);
        return ResponseEntity.ok(requirements);
    }
    
    /**
     * 根据状态查找需求列表
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<RequirementDTO>> findRequirementsByStatus(@PathVariable RequirementStatus status) {
        List<RequirementDTO> requirements = requirementApplicationService.findByStatus(status);
        return ResponseEntity.ok(requirements);
    }
    
    /**
     * 根据优先级查找需求列表
     */
    @GetMapping("/priority/{priority}")
    public ResponseEntity<List<RequirementDTO>> findRequirementsByPriority(@PathVariable RequirementPriority priority) {
        List<RequirementDTO> requirements = requirementApplicationService.findByPriority(priority);
        return ResponseEntity.ok(requirements);
    }
    
    /**
     * 查找所有需求
     */
    @GetMapping
    public ResponseEntity<List<RequirementDTO>> findAllRequirements() {
        List<RequirementDTO> requirements = requirementApplicationService.findAll();
        return ResponseEntity.ok(requirements);
    }
    
    // ==================== 文档相关API ====================
    
    /**
     * 为需求添加参考文档
     */
    @PostMapping("/{requirementId}/documents")
    public ResponseEntity<?> addDocumentToRequirement(
            @PathVariable Long requirementId,
            @Valid @RequestBody AddDocumentRequest request) {
        try {
            // TODO: 从认证上下文获取当前用户作为上传者
            String uploader = "system"; // 临时使用系统默认值
            String documentType = "general"; // 默认文档类型
            
            ReferenceDocumentDTO document = referenceDocumentApplicationService.createReferenceDocument(
                requirementId.toString(),
                request.getTitle(),
                request.getUrl(),
                request.getDescription(),
                documentType,
                uploader
            );
            return ResponseEntity.status(HttpStatus.CREATED).body(document);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 获取需求的所有参考文档
     */
    @GetMapping("/{requirementId}/documents")
    public ResponseEntity<List<ReferenceDocumentDTO>> getRequirementDocuments(@PathVariable Long requirementId) {
        try {
            List<ReferenceDocumentDTO> documents = referenceDocumentApplicationService.findByRequirementId(requirementId.toString());
            return ResponseEntity.ok(documents);
        } catch (BusinessException e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 删除需求的参考文档
     */
    @DeleteMapping("/{requirementId}/documents/{documentId}")
    public ResponseEntity<?> removeDocumentFromRequirement(
            @PathVariable Long requirementId,
            @PathVariable String documentId) {
        try {
            referenceDocumentApplicationService.deleteReferenceDocument(documentId);
            return ResponseEntity.noContent().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}